package com.biz.impl;


import com.bean.Goods;
import com.bean.Orders;
import com.bean.Role;
import com.bean.User;
import com.biz.GoodsBizService;

import com.dto.goods.GoodsBaseInfoDTO;
import com.dto.goods.GoodsUpdateDTO;
import com.exception.*;

import com.myenum.BizEnumData;
import com.myenum.BizEnumString;
import com.myenum.ExceptionEnum;
import com.myenum.RoleEnum;
import com.servicedao.*;

import com.utils.PageUtil;
import com.utils.TransactionUtil;
import com.utils.buildutil.GoodsBuildUtil;
import com.utils.buildutil.UserBuildUtil;
import com.utils.checkutil.GoodsCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author FatterShadystart
 * @create 2023-02-09 14:41
 */
@Service
@Slf4j
public class GoodsBizServiceImpl implements GoodsBizService {
    @Resource
    private GoodsService goodsService;

    @Resource
    private SeckillService seckillService;

    @Resource
    private OrdersService ordersService;

    @Resource
    private OrderGoodsService orderGoodsService;

    @Resource
    private SeckillGoodsService seckillGoodsService;



    @Resource
    private TransactionTemplate transactionTemplate;

    private static final Integer RESULT_RETURN_NUM = 1;



    @Override
    public Map<String, Object> queryGoodsByCondition(GoodsBaseInfoDTO goodsBaseInfoDTO) {
        List<Goods> goodsList = GoodsBuildUtil.buildGoodsList(goodsBaseInfoDTO.getGoods());
        Map<String, Object> resultMap = new HashMap();
        Map<String, Integer> pageStartAndEnd = PageUtil.getPageStartAndEnd(goodsBaseInfoDTO.getBaseInfoDTO());
        Integer start = pageStartAndEnd.get(BizEnumString.START.getMsg());
        Integer end = pageStartAndEnd.get(BizEnumString.END.getMsg());
        //查询GoodsList
        List<Goods> goodsListQuery = goodsService.selectGoodsListByCondition(goodsList, start, end);
        if (CollectionUtils.isEmpty(goodsListQuery)) {
            resultMap.put("goodsRoleList", null);
            resultMap.put("allGoodsCount", BizEnumData.DEFAULT_QUERY_COUNT.getData());
            return resultMap;
        }
        goodsListQuery= GoodsCheckUtil.subStringPicPath(goodsListQuery);

        //查询总记录数
        Integer allGoodsCount = goodsService.selectGoodsListByCondition(goodsList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END_MAX.getData()).size();
        log.info("goodsListQuery:{}", goodsListQuery);
        log.info("allGoodsCount:{}", allGoodsCount);
        resultMap.put("goodsListQuery", goodsListQuery);
        resultMap.put("allGoodsCount", allGoodsCount);
        return resultMap;

    }

    @Override
    public Map<String, Object> queryGoodsAllByPage(GoodsBaseInfoDTO goodsBaseInfoDTO) {
        Map<String, Object> resultMap = new HashMap();
        Map<String, Integer> pageStartAndEnd = PageUtil.getPageStartAndEnd(goodsBaseInfoDTO.getBaseInfoDTO());
        Integer start = pageStartAndEnd.get(BizEnumString.START.getMsg());
        Integer end = pageStartAndEnd.get(BizEnumString.END.getMsg());
        //查询GoodsList
        List<Goods> goodsList = goodsService.selectAllGoodsList(start, end);
        if(!CollectionUtils.isEmpty(goodsList)){
            goodsList= GoodsCheckUtil.subStringPicPath(goodsList);
        }
         //查询总记录数
        Integer allGoodsCount = goodsService.selectAllGoodsList( BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END_MAX.getData()).size();
        log.info("goodsList:{}", goodsList);
        log.info("allGoodsCount:{}", allGoodsCount);
        resultMap.put("goodsList", goodsList);
        resultMap.put("allGoodsCount", allGoodsCount);
        return resultMap;
    }


    public void insertGoods(GoodsBaseInfoDTO goodsBaseInfoDTO) throws InsertException {
        Goods goods = goodsBaseInfoDTO.getGoods();
        List<Goods> goodsList = GoodsBuildUtil.buildGoodsListInsert(goods);
        //判断是否已有这个商品，有就抛异常
        if (!ObjectUtils.isEmpty(goodsService.selectGoodsListByGoodsName(goodsList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END.getData()))) {
            throw new InsertException(ExceptionEnum.GOODS_SELECT_RETURN_SAME_EXCEPTION.getErrorMsg());
        }
        TransactionUtil.checkTransactionInsert(transactionTemplate.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus transactionStatus) {
                try {
                    //插入商品
                    Integer goodsInsResult = goodsService.insertBatch(goodsList);
                    log.info("goodsInsResult:{}", goodsInsResult);
                    if (!RESULT_RETURN_NUM.equals(goodsInsResult)) {
                        log.error("goodsInsResult:{}", goodsInsResult);
                        throw new ISQLException(ExceptionEnum.INSERT_RETURN_LINE_EXCEPTION.getErrorMsg());
                    }
                } catch (ISQLException e) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    log.error("e:{}", e.getMessage());
                    return false;
                }
                return true;
            }
        }));


    }

    @Override
    public void deleteBatchGoods(List<Long> goodsIdList, Long updatorId) throws DeleteException {
        List<Goods> goodsList = GoodsBuildUtil.buildGoodsListByGoodsIdList(goodsIdList);
        //查询是否有该条商品
        List<Goods> goodsListQuery = goodsService.selectGoodsList(goodsList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END_MAX.getData());
        //如果没有该商品就抛异常
        if (CollectionUtils.isEmpty(goodsListQuery)) {
            throw new DeleteException(ExceptionEnum.GOODS_DELETE_RETURN_NO_VALUE_EXCEPTION.getErrorMsg());
        }
        //进行updatorId的设置
        goodsListQuery.forEach(
                goods -> {
                    goods.setUpdatorId(updatorId);
                }
        );
        //在这一步的删除，删除的商品依旧能被订单已完成的状态查询出来 后续增加商品上下架功能再进行逻辑更改（v1.1会迭代）
        TransactionUtil.checkTransactionDelete(transactionTemplate.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus transactionStatus) {
                try {
                    //删goods表
                    Integer goodsDeleteResult = goodsService.deleteBatch(goodsListQuery);
                    log.info("goodsDeleteResult:{}", goodsDeleteResult);
                    if (!Integer.valueOf(goodsListQuery.size()).equals(goodsDeleteResult)) {
                        log.error("goodsDeleteResult:{}", goodsDeleteResult);
                        throw new ISQLException(ExceptionEnum.DELETE_RETURN_LINE_EXCEPTION.getErrorMsg());
                    }
                } catch (ISQLException e) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    log.error("e:{}", e.getMessage());
                    return false;
                }
                return true;
            }
        }));
    }

    @Override
    public void updateGoods(GoodsUpdateDTO goodsUpdateDTO, Long updatorId) throws UpdateException {
        List<Goods> goodsList = GoodsBuildUtil.buildGoodsList(goodsUpdateDTO.getGoods());
        //查询是否有该条商品
        List<Goods> goodsListQuery = goodsService.selectGoodsList(goodsList, BizEnumData.DEFAULT_START.getData(), BizEnumData.DEFAULT_END_MAX.getData());
        //如果没有该商品就抛异常
        if (CollectionUtils.isEmpty(goodsListQuery)) {
            throw new UpdateException(ExceptionEnum.GOODS_UPDATE_RETURN_NO_VALUE_EXCEPTION.getErrorMsg());
        }
        //拷贝数据用于更新
        Goods goodsListItem = goodsList.get(0);
        Goods goodsListQueryItem = goodsListQuery.get(0);
        goodsListQueryItem.setGoodsName(goodsListItem.getGoodsName());
        goodsListQueryItem.setGoodsPrice(goodsListItem.getGoodsPrice());
        goodsListQueryItem.setGoodsDisc(goodsListItem.getGoodsDisc());
        goodsListQueryItem.setGoodsStock(goodsListItem.getGoodsStock());
        goodsListQueryItem.setGoodsSeckillStock(goodsListItem.getGoodsSeckillStock());
        goodsListQueryItem.setGoodsNormalStock(goodsListItem.getGoodsNormalStock());
        if(StringUtils.isEmpty(goodsListItem.getGoodsPic())){
            goodsListQueryItem.setGoodsPic(null);
        }else {
            goodsListQueryItem.setGoodsPic(goodsListItem.getGoodsPic());
        }
        goodsListQueryItem.setUpdatorId(updatorId);
        //在这一步的删除，删除的商品依旧能被订单已完成的状态查询出来 后续增加商品上下架功能再进行逻辑更改（v1.1会迭代）
        TransactionUtil.checkTransactionUpdate(transactionTemplate.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus transactionStatus) {
                try {
                    //更新goods表
                    Integer goodsUpdateResult = goodsService.updateBatch(goodsListQuery);
                    log.info("goodsUpdateResult:{}", goodsUpdateResult);
                    if (!Integer.valueOf(goodsListQuery.size()).equals(goodsUpdateResult)) {
                        log.error("goodsUpdateResult:{}", goodsUpdateResult);
                        throw new ISQLException(ExceptionEnum.DELETE_RETURN_LINE_EXCEPTION.getErrorMsg());
                    }
                } catch (ISQLException e) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    log.error("e:{}", e.getMessage());
                    return false;
                }
                return true;
            }
        }));
    }
}